import {h, resolveComponent} from 'vue'
// 处理routes
export function filterRoute(route) {
    // 重写route component
    let _route = {
        path: route.path,
        name: route.name,
        component: route.component ? () => import('@/views'+route.component) : {render: () => h(resolveComponent("router-view"))},
        meta: {
            id: route.id,
            title: route.title,
            icon: route.icon ? route.icon : '',
            type: route.type,
            isOpen: route.isOpen ? route.isOpen : 0
        }
    }
    if(route.children){
        _route.children = []
        route.children.forEach(item => {
            _route.children.push(filterRoute(item))
        })
    }
    return _route
}

//构建树结构(pid ：menu proute: route)
export function createTreeData(data, parentId = 'pid', children = 'children') {
    let result = []
    if (!Array.isArray(data)) {
        return result
    }
    let node = JSON.parse(JSON.stringify(data))
    node.forEach(item => delete item[children])//已经有的话就删掉
    let map = {}
    node.forEach(item => map[item.id] = item)
    let newNode = []
    node.forEach(dt => {
        let parents = map[dt[parentId]]
        parents ? ((parents[children]) || (parents[children] = [])).push(dt) : newNode.push(dt)
    })
    return newNode
}
// 获取当前路由菜单完整路径
export function findParent(data, id){
    let result = []
    let forFn = function (list,_id){
        for (let i in list) {
            let item = list[i]
            if (item.id === _id) {
                //将查找到的目标数据加入结果数组中
                result.unshift(item)
                return true
            }
            if (item.children && item.children.length > 0) {
                let node = forFn(item.children, _id)
                if (node) {
                    result.unshift(item)
                    return true
                }
            }
        }
        //走到这说明没找到目标
        return false
    }
    forFn(data,id)
    return result
}
